package net.entelijan.cobean.core.impl;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.HashMap;

import net.entelijan.cobean.core.IRemovable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class AbstractComponentBean implements
		IPropertyChangeListenerAware {

	private Log log = LogFactory.getLog(AbstractComponentBean.class);

	protected PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
			this);
	private HashMap<String, PropertyChangeListener> listeners = new HashMap<String, PropertyChangeListener>();

	public AbstractComponentBean() {
		super();
	}

	@Override
	public void setPropertyChangeListener(INamedPropertyChangeListener listener) {
		PropertyChangeListener prevListener = listeners.get(listener.getName());
		if (prevListener != null) {
			if (prevListener instanceof IRemovable) {
				((IRemovable) prevListener).remove();
			}
			this.propertyChangeSupport
					.removePropertyChangeListener(prevListener);
			log.debug("[" + getClass().getName()
					+ "#setPropertyChangeListener] removed revious listener '"
					+ prevListener + "'");
		}
		this.listeners.put(listener.getName(), listener);
		this.propertyChangeSupport.addPropertyChangeListener(listener);
		log
				.debug("[" + getClass().getName()
						+ "#setPropertyChangeListener] set listener '"
						+ listener + "'");
	}

	@Override
	public void removePropertyChangeListener(String name) {
		PropertyChangeListener prevListener = listeners.get(name);
		if (prevListener != null) {
			if (prevListener instanceof IRemovable) {
				((IRemovable) prevListener).remove();
			}
			this.propertyChangeSupport
					.removePropertyChangeListener(prevListener);
			this.listeners.remove(name);
			log
					.debug("["
							+ getClass().getName()
							+ "#removePropertyChangeListener] removed listener with name '"
							+ name + " from '" + this + "'");
		} else {
			log
					.debug("["
							+ getClass().getName()
							+ "#removePropertyChangeListener] found no listener with name '"
							+ name + "' from '" + this + "' -> nothing done");
		}
	}

	@Override
	public void firePropertyChanged() {
		// nothing to do
	}

}
